package com.example.board.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.example.board.mapper.DistributorMapper;
import com.example.board.pojo.dto.UserDto;
import com.example.board.pojo.vo.*;
import com.example.board.service.DistributorService;
import com.example.board.util.DateQuery;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class DistributorServiceImpl implements DistributorService {

    private final DistributorMapper distributorMapper;

    @Override
    public Map<String, Object> getAllCityAmount() {
        //总订单
        Integer orders = distributorMapper.findAllCityOrders();
        //总用户
        Integer customer = distributorMapper.findAllCityCustomer();
        Map<String,Object> map = new HashMap<>();
        map.put("total",customer);
        map.put("finish",orders);

        return map;
    }

    @Override
    public CityOrder getCityOrder(String province, String region, String targetOrder) {
        if (StringUtils.isEmpty(targetOrder)) {
            targetOrder = "10000";
        }


        //1.具有转换功能的对象
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //3.LocalDate发动，将字符串转换成  df格式的LocalDateTime对象，的功能
        LocalDateTime mothStart = LocalDateTime.parse(DateQuery.getMothStart(), df);
        LocalDateTime mothEnd = LocalDateTime.parse(DateQuery.getMothEnd(), df);

        List<CityOrder> cityOrder1 = distributorMapper.getCityOrder(province, region, mothStart,mothEnd);

        CityOrder cityOrder = new CityOrder();


        cityOrder.setAreaValue(cityOrder1.stream().mapToInt(CityOrder::getAreaValue).sum());

        cityOrder.setFinish(cityOrder1.stream().mapToInt(CityOrder::getAreaValue).sum());

        if (StringUtils.isEmpty(province) && StringUtils.isEmpty(region)) {
            cityOrder.setArea("全国");
            cityOrder.setDistrict("全国");
        } else {
            if (StringUtils.isNotEmpty(region)) {
                cityOrder.setArea(region);
            } else {
                cityOrder.setArea(province);
            }

            cityOrder.setDistrict(region);
        }
        cityOrder.setChartData(new BigDecimal(cityOrder.getAreaValue()).divide(BigDecimal.valueOf(Long.parseLong(targetOrder)), 2, RoundingMode.HALF_UP));
        cityOrder.setTarget(targetOrder);
        return cityOrder;
    }

    @Override
    public CityOrderRate getCityOrderIncrease(String province,
                                              String region,
                                              String time,
                                              String teamName) throws ParseException {

        // 首先根据前端传来的时间区间，查询出区间中所有的月份；
        String startDate = null;
        String endDate = null;

        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        if (StringUtils.isEmpty(time)) {
            startDate = DateUtil.format(DateQuery.getCurrYearFirst(), format1);
            endDate = DateUtil.format(DateQuery.getCurrYearLast(), format1);

        }
        if (StringUtils.isNotEmpty(time)) {

            endDate = DateUtil.format(DateQuery.getYearLast(Integer.parseInt(time)), format1);
            startDate = DateUtil.format(DateQuery.getYearFirst(Integer.parseInt(time)), format1);

        }


        //1.具有转换功能的对象
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //3.LocalDate发动，将字符串转换成  df格式的LocalDateTime对象，的功能
        LocalDateTime startLocalTime = LocalDateTime.parse(startDate, df);
        LocalDateTime endLocalTime = LocalDateTime.parse(endDate, df);

        //查询每月数量
        List<CityOrderMoth> cityOrderRate
                = distributorMapper.findCityOrderRate(province, region,
                startLocalTime, endLocalTime, teamName);

        CityOrderRate cityOrder = new CityOrderRate();

        //订单总数
        if (CollectionUtils.isNotEmpty(cityOrderRate)) {
            //总订单数
            int sum = cityOrderRate.stream().mapToInt(CityOrderMoth::getData).sum();
            cityOrder.setFinish(sum );
        } else {
            cityOrder.setFinish(0);
        }

        if (StringUtils.isEmpty(province) && StringUtils.isEmpty(region)) {
            cityOrder.setDistrict("全国");
            cityOrder.setArea("全国");
        } else {
            if (StringUtils.isNotEmpty(region)) {
                if (StringUtils.isNotEmpty(teamName)) {
                    cityOrder.setArea(region + "-" + teamName);
                } else {
                    cityOrder.setArea(region);
                }
            } else {
                cityOrder.setArea(province);
            }

            cityOrder.setDistrict(region);
        }

        List<Date> lDate = DateQuery.getMonths(startDate, endDate);

        List<CityOrderMoth> experienceDayResList = new ArrayList<>(cityOrderRate);

        for (Date date : lDate) {
            // 当前日期不存在则新增
            String dateStr = DateUtil.format(date, "yyyy-MM");
            // 进行匹配
            if (!experienceDayResList.stream().filter(item -> dateStr.equals(item.getName())).findAny().isPresent()) {
                CityOrderMoth experienceDayRes = CityOrderMoth.builder()
                        .name(dateStr)
                        .data(0)
                        .area(province)
                        .district(region)
                        .build();
                experienceDayResList.add(experienceDayRes);
            }
        }
        List<CityOrderMoth> collect = experienceDayResList.stream().sorted(Comparator.comparing(CityOrderMoth::getName)).collect(Collectors.toList());
        cityOrder.setChartData(collect);

        //已下单数
        Integer orderCity = distributorMapper.findCityOrders(province, region, startLocalTime, endLocalTime, teamName);
        cityOrder.setTotal(orderCity);

        //取消数量
        Integer orderCityFalse = distributorMapper.findCityOrdersFalse(province, region, startLocalTime, endLocalTime, teamName);
        cityOrder.setCancel(orderCityFalse == null ? 0 : orderCityFalse);

        String moth = DateQuery.getMothStart().split(" ")[0].split("-")[1];

        if (Integer.parseInt(moth) >= 1) {

            BigDecimal successOrder = collect.get(Integer.parseInt(moth) - 1)
                    == null ? new BigDecimal(0) : new BigDecimal(collect.get(Integer.parseInt(moth) - 1).getData());
            BigDecimal successOrder1 = collect.get(Integer.parseInt(moth) - 2)
                    == null ? new BigDecimal(0) : new BigDecimal(collect.get(Integer.parseInt(moth) - 2).getData());

            System.out.println("successOrder1 : " + successOrder1);
            if (successOrder1.equals(new BigDecimal(0))) {
                cityOrder.setIncRate(successOrder);
            } else {
                BigDecimal rate = (successOrder.subtract(successOrder1)).divide(successOrder1, 2, RoundingMode.HALF_UP);

                cityOrder.setIncRate(rate);
            }

        } else {
            BigDecimal bigDecimal = new BigDecimal(0);
            cityOrder.setIncRate(bigDecimal);
        }


        for (int i = 0; i < cityOrder.getChartData().size(); i++) {
            String[] s = cityOrder.getChartData().get(i).getName().split("-");
            cityOrder.getChartData().get(i).setName(s[1].replaceFirst("^0*", "") + "月");
        }

        return cityOrder;
    }


    @Override
    public CityRate getCityOrderRate(String province,
                                     String region) {


        //1.具有转换功能的对象
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        LocalDateTime startM = LocalDateTime.parse(DateQuery.getMothStart(), df);
        LocalDateTime endM = LocalDateTime.parse(DateQuery.getMothEnd(), df);
        LocalDateTime startMonth = LocalDateTime.parse(DateQuery.getMothStartLast(), df);
        LocalDateTime endMonth = LocalDateTime.parse(DateQuery.getMothEndLast(), df);

        //根据城市查询销售 得到用户id 这月下单
        List<UserDto> cityRatesNow = distributorMapper.findCityOrderRecord(province, region, startM, endM);
        //总单量
        Long totalOrder = 0L;
        Long totalOrderRate = 0L;
        if (CollectionUtils.isNotEmpty(cityRatesNow)){
            totalOrder =cityRatesNow.stream().mapToInt(UserDto::getTotalOrder).count();
            System.out.println("下单数量： "+totalOrder);
            List<Long> userRecordIds = cityRatesNow.stream().map(UserDto::getUserRecordId).collect(Collectors.toList());
            //查询上月下单
            List<UserDto> cityRates = distributorMapper.findCityOrderRates(userRecordIds, startMonth, endMonth);
            //返单数量
            totalOrderRate = cityRates.stream().filter(x -> x.getTotalOrder() > 0).mapToInt(UserDto::getTotalOrder).count();
            System.out.println("返单数量： "+totalOrderRate);
        }

        CityRate cityRate = new CityRate();
        if (StringUtils.isEmpty(province) && StringUtils.isEmpty(region)) {
            cityRate.setArea("全国");
            cityRate.setDistrict("全国");
        } else {
            if (StringUtils.isNotEmpty(region)) {
                cityRate.setArea(region);
            } else {
                cityRate.setArea(province);
            }
            cityRate.setDistrict(region);
        }
        cityRate.setAreaValue(new BigDecimal(0));
        cityRate.setChartData(new BigDecimal(0));

        if (totalOrder != 0){
            cityRate.setAreaValue(new BigDecimal(totalOrderRate).divide(new BigDecimal(totalOrder),2, RoundingMode.HALF_UP));
            cityRate.setChartData(new BigDecimal(totalOrderRate).divide(new BigDecimal(totalOrder),2, RoundingMode.HALF_UP));
        }

        return cityRate;
    }


    @Override
    public NumberRate getCityNumberRate(String province,
                                        String region,
                                        String time,
                                        String teamName) throws ParseException {

        NumberRate numberRate = new NumberRate();
        // 首先根据前端传来的时间区间，查询出区间中所有的月份；

        System.out.println("time时间: " + time);
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String startDate = null;
        String endDate = null;
        if (StringUtils.isEmpty(time)) {
            startDate = DateUtil.format(DateQuery.getCurrYearFirst(), format1);
            endDate = DateUtil.format(DateQuery.getCurrYearLast(), format1);

        }
        if (StringUtils.isNotEmpty(time)) {

            endDate = DateUtil.format(DateQuery.getYearLast(Integer.parseInt(time)), format1);
            startDate = DateUtil.format(DateQuery.getYearFirst(Integer.parseInt(time)), format1);
        }

        //1.具有转换功能的对象
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //3.LocalDate发动，将字符串转换成  df格式的LocalDateTime对象，的功能
        LocalDateTime startLocalTime = LocalDateTime.parse(startDate + "", df);
        LocalDateTime endLocalTime = LocalDateTime.parse(endDate + "", df);

        //查询客户数量
        List<NumberAmount> numberAmounts = distributorMapper.findCityNumber(province, region, startLocalTime, endLocalTime, teamName);

        numberRate.setTotal(0L);
        if (CollectionUtils.isNotEmpty(numberAmounts)) {
            //总订单数
            long count = numberAmounts.stream().mapToLong(NumberAmount::getData).sum();
            numberRate.setTotal(count);
        }

        List<Date> lDate = DateQuery.getMonths(startDate, endDate);

        List<NumberAmount> experienceDayResList = new ArrayList<>(numberAmounts);

        for (Date date : lDate) {
            // 当前日期不存在则新增
            String dateStr = DateUtil.format(date, "yyyy-MM");
            // 进行匹配
            if (!experienceDayResList.stream().filter(item -> dateStr.equals(item.getName())).findAny().isPresent()) {
                NumberAmount experienceDayRes = NumberAmount.builder()
                        .name(dateStr)
                        .data(0L)
                        .build();
                experienceDayResList.add(experienceDayRes);
            }
        }

        List<NumberAmount> collect = experienceDayResList.stream().sorted(Comparator.comparing(NumberAmount::getName)).collect(Collectors.toList());


        if (StringUtils.isEmpty(province) && StringUtils.isEmpty(region)) {
            numberRate.setArea("全国");
            numberRate.setDistrict("全国");
            numberRate.setChartData(collect);
        } else {
            if (StringUtils.isNotEmpty(teamName)) {
                numberRate.setArea(province + "-" + region + "-" + teamName);
            } else {
                numberRate.setArea(province + "-" + region);
            }

            numberRate.setDistrict(region);
            numberRate.setChartData(collect);

        }

        String moth = DateQuery.getMothStart().split(" ")[0].split("-")[1];

        if (Integer.parseInt(moth) >= 1) {

            BigDecimal successOrder = collect.get(Integer.parseInt(moth) - 1)
                    == null ? new BigDecimal(0) : new BigDecimal(collect.get(Integer.parseInt(moth)).getData());
            BigDecimal successOrder1 = collect.get(Integer.parseInt(moth) - 2)
                    == null ? new BigDecimal(0) : new BigDecimal(collect.get(Integer.parseInt(moth) - 2).getData());

            if (successOrder1.equals(new BigDecimal(0))) {
                numberRate.setIncRate(successOrder);
            }
            BigDecimal rate = new BigDecimal(0);
            if (!successOrder1.equals(new BigDecimal(0))) {
                rate = (successOrder.subtract(successOrder1)).divide(successOrder1, 2, RoundingMode.HALF_UP);

            }
            System.out.println("rate: " + rate);
            numberRate.setIncRate(rate);
        } else {
            numberRate.setIncRate(new BigDecimal(0));
        }


        for (int i = 0; i < numberRate.getChartData().size(); i++) {
            String[] s = numberRate.getChartData().get(i).getName().split("-");
            numberRate.getChartData().get(i).setName(s[1].replaceFirst("^0*", "") + "月");
        }

        return numberRate;
    }


    @Override
    public List<TopSaleAchievement> getTopSaleAchievement(String province, String region, String teamName, String startTime) {
        LocalDate someStart = null;
        LocalDate someEnd = null;
        LocalDate someStartLast = null;
        LocalDate someEndLast = null;
        if (StringUtils.isEmpty(startTime)) {
            String mothNow =  (DateTime.now() + "").split(" ")[0].split("-")[0] +(DateTime.now() + "").split(" ")[0].split("-")[1];
            String mothLast =  (DateTime.now() + "").split(" ")[0].split("-")[0] + (Integer.parseInt((DateTime.now() + "").split(" ")[0].split("-")[1])-1);
            //这月的
            someStart = DateQuery.getMothSomeStart(mothNow);
            someEnd = DateQuery.getMothSomeEnd(mothNow);
            //上月的
            someStartLast = DateQuery.getMothSomeStart(mothLast);
            someEndLast = DateQuery.getMothSomeEnd(mothLast);

        }
        if (StringUtils.isNotEmpty(startTime) && !startTime.substring(4).equals("01")){
            someStart = DateQuery.getMothSomeStart(startTime);
            someEnd = DateQuery.getMothSomeEnd(startTime);

            //上月的
            someStartLast = DateQuery.getMothSomeStart((Integer.parseInt(startTime)-1)+"");
            someEndLast = DateQuery.getMothSomeEnd((Integer.parseInt(startTime)-1)+"");
        }
        if (StringUtils.isNotEmpty(startTime) && startTime.substring(4).equals("01")){
            someStart = DateQuery.getMothSomeStart(startTime);
            someEnd = DateQuery.getMothSomeEnd(startTime);

            //上年的最后一个月的
            someStartLast = DateQuery.getMothSomeStart((Integer.parseInt(startTime)-89)+"");
            someEndLast = DateQuery.getMothSomeEnd((Integer.parseInt(startTime)-89)+"");
        }

        //1.具有转换功能的对象
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        //3.LocalDate发动，将字符串转换成  df格式的LocalDateTime对象，的功能
        LocalDateTime startLocalTime = LocalDateTime.parse(someStart+" 00:00:00", df);
        LocalDateTime endLocalTime = LocalDateTime.parse(someEnd+" 00:00:00", df);

        LocalDateTime startLocalTimeLast = LocalDateTime.parse(someStartLast+" 00:00:00", df);
        LocalDateTime endLocalTimeLast = LocalDateTime.parse(someEndLast+" 00:00:00", df);

        List<TopSaleAchievement> topSaleStaticVos = new ArrayList<>();

        //查询销售人员姓名，id和地址
        List<UserDto> userDital = distributorMapper.findUserDital(province, region, teamName);
        if (CollectionUtils.isNotEmpty(userDital)){
            //根据id 查询用户的本周总金额
            List<Long> userIds = userDital.stream().map(UserDto::getId).collect(Collectors.toList());
            List<UserDto> userDetileMoney = distributorMapper.findAllMoneyWeek(userIds, startLocalTime,endLocalTime);
            //查询本周下单金额
            List<UserDto> userDetileMoneyAll = distributorMapper.findAllMoneyWeekAll(userIds, startLocalTime,endLocalTime);

            //查询新增客户
            List<UserDto> customerNew = distributorMapper.findCustomerNew(userIds,  startLocalTime,endLocalTime);

            //查询总用户数
            List<UserDto> allCustomer = distributorMapper.findAllCustomer(userIds);

            //查询当月下单销售总单
            List<UserDto> orderNumber = distributorMapper.findOrderNumberNowMothAndUID(userIds, startLocalTime, endLocalTime);

            //这月下单的人
            List<UserDto> orderMoth = distributorMapper.findOrderMoth(userIds, startLocalTime, endLocalTime);
            Map<Long, Long> userRates = new HashMap<>();

            if (CollectionUtils.isNotEmpty(orderMoth)){
                //查上月下单的人
                List<Long> userRecordIds = orderMoth.stream().map(UserDto::getUserRecordId).collect(Collectors.toList());
                List<UserDto> userRate = distributorMapper.findUserRate(userRecordIds, startLocalTimeLast, endLocalTimeLast);
                if (CollectionUtils.isNotEmpty(userRate)){
                    // 先查的本月返单的用户
                    // TODO:无论返单多少次算一单 后续可能按下单数来 ，改为先查上月下单用户，在查本月下单用户，用sum
                    userRates = userRate.stream().filter(x -> x.getTotalOrder() > 0).collect(Collectors.groupingBy(UserDto::getId, Collectors.counting()));
                }
            }
            //凑数据
            for (UserDto userDto : userDital) {
                TopSaleAchievement topSaleStaticVo = new TopSaleAchievement();
                topSaleStaticVo.setCustomerTotal(0);
                topSaleStaticVo.setCustomerNew(0);
                topSaleStaticVo.setTransactionAmount(0.00);
                topSaleStaticVo.setAvatarUrl(userDto.getAvatar());
                topSaleStaticVo.setId(userDto.getId());
                topSaleStaticVo.setOrderAmount(0.00);
                topSaleStaticVo.setRateReturn(new BigDecimal(0));
                topSaleStaticVo.setSalesman(userDto.getUserName());
//            topSaleStaticVo.setTeamName(userDetile.getProvince() + "-" + userDetile.getCity() + "-" + userDetile.getDistrict());
                topSaleStaticVo.setTeamName(userDto.getName());
//                topSaleStaticVo.setTop();
                topSaleStaticVo.setRepurchaseNumber(0L);
                topSaleStaticVo.setTeamColor("");

                //总金额 userDetileMoneyAll
                if (CollectionUtils.isNotEmpty(userDetileMoney)){
                    for (UserDto detile : userDetileMoney) {
                        if (userDto.getId().equals(detile.getId())) {
                            topSaleStaticVo.setTransactionAmount(detile.getOrderAmountWeek());
                            break;
                        }
                    }
                }

                if (CollectionUtils.isNotEmpty(userDetileMoneyAll)){
                    for (UserDto detile : userDetileMoneyAll) {
                        if (userDto.getId().equals(detile.getId())) {
                            topSaleStaticVo.setOrderAmount(detile.getOrderAmountWeekAll());
                            break;
                        }
                    }
                }


                //新增用户数
                if (CollectionUtils.isNotEmpty(customerNew)){
                    for (UserDto detile : customerNew) {
                        if (userDto.getId().equals(detile.getId())) {
                            topSaleStaticVo.setCustomerNew(detile.getCustomerWeek());
                            break;
                        }
                    }
                }

                //总用户数
                if (CollectionUtils.isNotEmpty(allCustomer)){
                    for (UserDto detile : allCustomer) {
                        if (userDto.getId().equals(detile.getId())) {
                            topSaleStaticVo.setCustomerTotal(detile.getCustomer());
                            break;
                        }
                    }
                }

                //返单率
                //返单数
                Long aDouble = 0L;
                if (CollectionUtils.isNotEmpty(userRates) && userRates.get(userDto.getId()) != null) {
                    aDouble = userRates.get(userDto.getId());
                }
//                System.out.println("DistributorServiceImpl "+userRates.get(userDto.getId())+" : "+ userDto.getId());

                if (CollectionUtils.isNotEmpty(orderNumber)) {
                    for (UserDto dto : orderNumber) {
                        //总下单的数量   //返单数量不为空
                        if (dto.getId().equals(userDto.getId()) && dto.getTotalOrder()!= null && dto.getTotalOrder() !=0 ) {
//                            System.out.println(userRates.get(userDto.getId())+" : "+ userDto.getId() +" : " + dto.getTotalOrder());
                            topSaleStaticVo.setRateReturn(new BigDecimal(aDouble).divide(BigDecimal.valueOf(dto.getTotalOrder()), 2, RoundingMode.HALF_UP));
                            break;
                        }
                    }

                }

                if (aDouble==null){
                    topSaleStaticVo.setRepurchaseNumber(0L);
                }else {
                    topSaleStaticVo.setRepurchaseNumber(aDouble);
                }
                topSaleStaticVos.add(topSaleStaticVo);

            }
            List<TopSaleAchievement> collect = topSaleStaticVos.stream()
                    .sorted(Comparator.comparingDouble(TopSaleAchievement::getTransactionAmount)
                            .reversed()).collect(Collectors.toList());
            int i = 1;
            for (TopSaleAchievement topSaleAchievement : collect) {
                topSaleAchievement.setTop(i);
                i++;
            }
            return collect;

        }


        return null;
    }
}
